//
//  DGAlignmentButton.m
//  DGUIKit
//
//  Created by Jinxiao on 8/19/16.
//  Copyright © 2016 debugeek. All rights reserved.
//

#import "DGAlignmentButton.h"

@implementation DGAlignmentButton

- (void)layoutSubviews {
    [super layoutSubviews];

    CGFloat titleWidth = CGRectGetWidth(self.titleLabel.bounds);
    CGFloat titleHeight = CGRectGetHeight(self.titleLabel.bounds);

    CGFloat imageWidth = CGRectGetWidth(self.imageView.bounds);
    CGFloat imageHeight = CGRectGetHeight(self.imageView.bounds);

    CGFloat center = CGRectGetWidth(self.bounds)/2;
    CGFloat imageCenterX = center - titleWidth/2;
    CGFloat titleCenterX = center + imageWidth/2;

    switch(_style) {
        case DGAlignmentButtonStyleImageTop: {
            self.titleEdgeInsets = UIEdgeInsetsMake(imageHeight/2 + _spacing/2, -(titleCenterX - center), -(imageHeight/2 + _spacing/2), titleCenterX - center);
            self.imageEdgeInsets = UIEdgeInsetsMake(-(titleHeight/2 + _spacing/2), center - imageCenterX, titleHeight/2 +  _spacing/2, -(center - imageCenterX));

            CGFloat verticalInset = ((titleHeight + _spacing + imageHeight) - MAX(titleHeight, imageHeight))/2;
            CGFloat horizontalInset = (MAX(titleWidth, imageWidth) - (titleWidth + imageWidth))/2;
            self.contentEdgeInsets = UIEdgeInsetsMake(verticalInset, horizontalInset, verticalInset, horizontalInset);

            break;
        }

        case DGAlignmentButtonStyleImageLeft: {
            self.titleEdgeInsets = UIEdgeInsetsMake(0, _spacing/2, 0, -_spacing/2);
            self.imageEdgeInsets = UIEdgeInsetsMake(0, -_spacing/2, 0, _spacing);

            self.contentEdgeInsets = UIEdgeInsetsMake(0, _spacing/2, 0, _spacing/2);

            break;
        }

        case DGAlignmentButtonStyleImageBottom: {
            self.titleEdgeInsets = UIEdgeInsetsMake(-(imageHeight/2 + _spacing/2), -(titleCenterX - center), imageHeight/2 + _spacing/2, titleCenterX - center);
            self.imageEdgeInsets = UIEdgeInsetsMake(titleHeight/2 + _spacing/2, center - imageCenterX, -(titleHeight/2 + _spacing/2), -(center - imageCenterX));

            CGFloat verticalInset = ((titleHeight + _spacing + imageHeight) - MAX(titleHeight, imageHeight))/2;
            CGFloat horizontalInset = (MAX(titleWidth, imageWidth) - (titleWidth + imageWidth))/2;
            self.contentEdgeInsets = UIEdgeInsetsMake(verticalInset, horizontalInset, verticalInset, horizontalInset);

            break;
        }

        case DGAlignmentButtonStyleImageRight: {
            self.titleEdgeInsets = UIEdgeInsetsMake(0, -(imageWidth + _spacing/2), 0, imageWidth + _spacing/2);
            self.imageEdgeInsets = UIEdgeInsetsMake(0, titleWidth + _spacing/2, 0, -(titleWidth + _spacing/2));

            self.contentEdgeInsets = UIEdgeInsetsMake(0, _spacing/2, 0, _spacing/2);

            break;
        }

        default:
            break;
    }
}

@end
